package com.oop.Viewer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class SimpleHttpServer {

    private final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

    private long delayTime;
    private long period;
    private HashMap<String, ArrayList<Viewer>> viewerMap;
    public SimpleHttpServer(long delayTime, long period) {
        this.viewerMap = new HashMap<>();
        this.delayTime = delayTime;
        this.period = period;
    }

    public void addViewer(String url, Viewer viewer) {
        if (!viewerMap.containsKey(url)) {
            viewerMap.put(url, new ArrayList<Viewer>());
        }
        viewerMap.get(url).add(viewer);
    }

    public void start() {
        service.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                for (String key : viewerMap.keySet()) {
                    ArrayList<Viewer> viewers = viewerMap.get(key);
                    for (Viewer viewer : viewers) {
                        viewer.outputInPlainText();
                    }
                }
            }
        }, delayTime, period, java.util.concurrent.TimeUnit.SECONDS);
    }
}
